export type DealStatus = 'deal-success'|'deal-failed'|'deal-suspended';
export class DealResult{
  dealStatus:DealStatus
  dealReturnValue:unknown

  constructor(dealStatus:DealStatus,dealReturnValue:unknown){
    this.dealStatus = dealStatus
    this.dealReturnValue = dealReturnValue
  }

  static success(dealReturnValue:unknown):DealResult{
    return new DealResult('deal-success',dealReturnValue)
  }

  static failed(dealReturnValue:unknown):DealResult{
    return new DealResult('deal-failed',  dealReturnValue)
  } 

  static suspended(dealReturnValue:unknown):DealResult{
    return new DealResult('deal-suspended',dealReturnValue)
  }

  static make(raw:unknown):DealResult{
    if (raw instanceof DealResult){
      return raw
    } 
    if (raw === undefined){
      return new DealResult('deal-suspended',undefined)
    }
    if (raw === null){
      return new DealResult('deal-success',null)
    }
    if (typeof raw === 'object'){
      if (raw instanceof Error){
        return new DealResult('deal-failed',raw)
      }
      let status = (raw as DealResult)['dealStatus'] as string|undefined
      if (status !== 'deal-success' && status !== 'deal-failed' && status !== 'deal-suspended'){
        status = undefined
      }
      if (status === undefined){
        return new DealResult('deal-success',raw)
      }
      if (Reflect.has(raw,'dealResult')){
        const result = (raw as DealResult)['dealReturnValue']
        return new DealResult(status,result)
      }
      return new DealResult(status,raw)
    }
    return new DealResult('deal-success',raw)
      
  }
}
